//
//  ByUIMineDateVC.m
//  itboye_shop_ios
//
//  Created by justiOS on 17/2/10.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByUIMineDataVC.h"

// vc
#import "ByUIAddressVC.h"
#import "ByUIChangeNickNameVC.h"
// net
#import "ByApiUser.h"

@interface ByUIMineDataVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *table;
@property (nonatomic, strong) NSArray *nameAry;
@property (nonatomic, strong) NSMutableArray *subnameAry;
@property (nonatomic, strong) UIImageView *iconView;
@property (nonatomic, strong) ByIconChooseDataSource *iconChooseDataSource;
@property (nonatomic, strong) NSString *sexStr;
@end

@implementation ByUIMineDataVC
#pragma mark getter
- (UITableView *)table {
    if (!_table) {
        _table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
        _table.delegate = self;
        _table.dataSource = self;
        _table.separatorStyle = UITableViewCellSeparatorStyleNone;
        _table.backgroundColor = TABLE_COLOR;
    }
    return _table;
}
- (NSArray *)nameAry {
    if (!_nameAry) {
        _nameAry = @[@"头像",@"昵称",@"性别",@"收货地址"];
    }
    return _nameAry;
}

- (NSMutableArray *)subnameAry {
    if (!_subnameAry) {
        NSArray *ary = @[@"昵称",@"男"];
        _subnameAry = [NSMutableArray arrayWithArray:ary];
    }
    return _subnameAry;
}
- (ByIconChooseDataSource *)iconChooseDataSource {
    if (!_iconChooseDataSource) {
        _iconChooseDataSource = [[ByIconChooseDataSource alloc] init];
        [_iconChooseDataSource fireWithViewController:self];
    }
    return _iconChooseDataSource;
}

- (UIImageView *)iconView {
    if (!_iconView) {
        _iconView = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 90, 7.5, 55, 55)];
        [_iconView setImageWithURL:[NSURL URLWithString:BY_USER.head] placeholderImage:DEFAULT_HEAD completed:nil];
        _iconView.layer.cornerRadius = _iconView.height / 2;
        _iconView.layer.masksToBounds = YES;
    }
    return _iconView;
}

- (NSString *)sexStr {
    if (!_sexStr) {
        _sexStr = BY_USER.sex;
    }
    return _sexStr;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"个人资料";
    [self addLeftBackBarButtonItem];
    [self.view addSubview:self.table];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self refreshInfo];
}

#pragma mark table delegate and dataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"normalCell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"normalCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.textLabel.text = self.nameAry[indexPath.row];
    cell.textLabel.font = FONT(16);
    cell.textLabel.textColor = [UIColor darkGrayColor];
    
    if (indexPath.row == self.nameAry.count - 1) {
        
    }else{
        
        if (indexPath.row == 0) {
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(20, 69.5, SCREEN_WIDTH - 20, 0.5)];
            line.backgroundColor = BY_LINE_COLOR;
            [cell addSubview:line];
            [cell addSubview:self.iconView];
        }
        if (indexPath.row == 1 || indexPath.row == 2) {
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(20, 43.5, SCREEN_WIDTH - 20, 0.5)];
            line.backgroundColor = BY_LINE_COLOR;
            [cell addSubview:line];
            cell.detailTextLabel.text = self.subnameAry[indexPath.row - 1];
        }
    }
    
    return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.nameAry.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 70;
    }else{
        return 44;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        [self.iconChooseDataSource makeConfigToSelectIcon];
        __weak typeof(self) weakself = self;
        [self.iconChooseDataSource setCompleteBlock:^(UIImage *image) {
            
            [weakself uploadIcon:image];
        }];
    }else if (indexPath.row == 1){
        ByUIChangeNickNameVC *vc = [[ByUIChangeNickNameVC alloc] init];
        [self by_normalPush:vc hasNavi:YES];
        
    }else if (indexPath.row == 2){
        // 创建ActionSheet
        NSString *albumButtonTitle = @"男";
        NSString *cameraButtonTitle = @"女";
        NSString *cancelButtonTitle = @"取消";
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        // 添加点击动作
        // 取消
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleCancel handler:nil];
        // 男
        UIAlertAction *albumAction = [UIAlertAction actionWithTitle:albumButtonTitle style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action)
                                      {
                                          if ([self.sexStr isEqualToString:@"0"]) {
                                              return;
                                          }
                                          self.sexStr = @"0";
                                          [self sexAction];
                                      }];
        // 女
        UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:cameraButtonTitle style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action)
                                       {
                                           if ([self.sexStr isEqualToString:@"1"]) {
                                               return;
                                           }
                                           self.sexStr = @"1";
                                           [self sexAction];
                                       }];
        
        // Add the actions.
        [alertController addAction:cancelAction];
        [alertController addAction:albumAction];
        [alertController addAction:cameraAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else if (indexPath.row == 3){
        ByUIAddressVC *vc = [[ByUIAddressVC alloc] init];
        [self by_normalPush:vc hasNavi:YES];
    }
}

#pragma mark - net
- (void)uploadIcon:(UIImage *)icon {
    
    // 上传头像
    [ByCoreToolAlert showLoadind:@"上传中" hasMasker:YES];
    [ByApiUser uploadImage:icon type:@"avatar" success:^(NSArray *success) {
        self.iconView.image = icon;
        NSDictionary *dic = success[0];
        ByModelUser *user = BY_USER;
        user.head = BOYE_IMAGE_URL_ORIGINAL(dic[@"id"]);
        [ByCacheUser setUserInfo:user];
        [ByCoreToolAlert showSuccessWithText:@"上传成功"];
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [ByCoreToolAlert showSuccessWithText:error.domain];
    }];
}

// 刷新信息
- (void)refreshInfo {
    
    
    NSString *nickname;
    NSString *sex;
    if (BY_USER.sex.integerValue == 0) {
        sex = @"男";
    }else{
        sex = @"女";
    }
    if (BY_USER.nickname.length > 0) {
        nickname = BY_USER.nickname;
    }else{
        nickname = @"昵称";
    }

    NSArray *ary = @[nickname,sex];
    [self.subnameAry removeAllObjects];
    [self.subnameAry addObjectsFromArray:ary];
    [self.table reloadData];
    
}

- (void)sexAction {
    ByModelUser *user = [ByCacheUser getUserInfo];
    ByNetParamsModel *model = [[ByNetParamsModel alloc] init];
    model.uid = user.uid;
    model.s_id = user.s_id;
    model.sex = self.sexStr;
    [ByApiUser updateUserInfo:model success:^(ByNetBaseResult *result) {
        user.sex = self.sexStr;
        [ByCacheUser setUserInfo:user];
        [self refreshInfo];
        [ByCoreToolAlert showSuccessWithText:result.msg];
    } failure:^(ByNetBaseResult *result) {
        self.sexStr = BY_USER.sex;
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];

    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
